﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CNRegex.Web.Base;
using CNRegex.Entity;
using CNRegex.Biz.BizAccess;
using Project.Common;
using CNRegex.Biz;
using CNRegex.Enum;

namespace CNRegex.Web.Controllers
{
	public class AdminRegexTutorialCatalogController : BaseController
	{
		private BizRegexTutorialCatalog bizRegexTutorialCatalog;
		private BizRegexTutorial bizRegexTutorial;
		private BizRegexTutorialCatalogContent bizRegexTutorialCatalogContent;
		public AdminRegexTutorialCatalogController()
		{
			bizRegexTutorialCatalog = BizFactory.Get<BizRegexTutorialCatalog>();
			bizRegexTutorial = BizFactory.Get<BizRegexTutorial>();
			bizRegexTutorialCatalogContent = BizFactory.Get<BizRegexTutorialCatalogContent>();
		}

		//
		// GET: /AdminRegexTutorialCatalog/
		public ActionResult Index(Guid id,int? level,Guid? parentID)
		{
			level = level ?? 0;
			IList<RegexTutorialCatalog> list = parentID == null ? bizRegexTutorialCatalog.ListBy(x => x.TutorialID == id && x.Level == level, x => x.OrderIndex, Enum.EnumOrder.ASC) : bizRegexTutorialCatalog.ListBy(x => x.TutorialID == id && x.Level == level && (x.ParentID == parentID.Value), x => x.OrderIndex, Enum.EnumOrder.ASC);
			ViewBag.Tutorial = bizRegexTutorial.GetByID(id);
			ViewBag.Level = level;
			ViewBag.ParentID = parentID == null ? "" : parentID.Value.ToString();
			return View(list);
		}

		[HttpPost]
		public ActionResult Save(RegexTutorialCatalog model)
		{
			bizRegexTutorialCatalog.SaveOrUpdate(model);
			return Content("");
		}

		[HttpPost]
		public ActionResult Delete(Guid id)
		{
			bizRegexTutorialCatalog.DeleteByID(id, NHibernate.NHibernateUtil.Guid);
			return Content("");
		}


		public ActionResult CatalogContent(Guid id)
		{
			var regexTutorialCatalogContent = bizRegexTutorialCatalogContent.ListBy(x => x.TutorialCatalogID == id, "", EnumOrder.ASC).FirstOrDefault();
			ViewBag.RegexTutorialCatalog = bizRegexTutorialCatalog.GetByID(id);
			return View(regexTutorialCatalogContent);
		}

		[HttpPost]
		[ValidateInput(false)]
		public ActionResult CatalogContent(RegexTutorialCatalogContent model)
		{
			if (!StringUtility.IsEmptyGuid(model.ID))
			{
				var originalModel = bizRegexTutorialCatalogContent.GetByID(model.ID);
				originalModel.Content = model.Content;
				originalModel.CreateDate = DateTime.Now;
				bizRegexTutorialCatalogContent.SaveOrUpdate(originalModel);
			}
			else
			{
				model.CreateDate = DateTime.Now;
				bizRegexTutorialCatalogContent.SaveOrUpdate(model);
			}
			return RedirectToAction("CatalogContent", new { id=model.TutorialCatalogID});
		}

	}
}
